package net.zjitc.controller;

import net.zjitc.pojo.CartItem;
import net.zjitc.pojo.Product;
import net.zjitc.pojo.User;
import net.zjitc.service.CartService;
import net.zjitc.service.Impl.CartServiceImpl;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/2.
 */
public class UserCart {
    CartService cartService=new CartServiceImpl();
    @URLMapping(url = "/findMyCart")
    public String findMyCart(HttpServletRequest request, HttpServletResponse response) {
        //判断用户是否登录
        User user= (User) request.getSession().getAttribute("user");
        if(user==null)
        {
            return "/WEB-INF/user/login.jsp";
        }

        List<CartItem> list=cartService.findByUid(user.getUid());
        request.setAttribute("list",list);

        Double total=0.0;
        if(list!=null)
        {
            for(CartItem i:list)
            {
                total=total+i.getProduct().getShop_price()*i.getQuantity();
            }
            request.setAttribute("total",total);
        }

        return "/WEB-INF/user/cart.jsp";
    }
    @URLMapping(url = "/addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response) {
        //判断用户是否登录
        User user= (User) request.getSession().getAttribute("user");
        if(user==null)
        {
            return "/WEB-INF/user/login.jsp";
        }
        else{
            Map<String, String[]> map = request.getParameterMap();

            CartItem cartItem=new CartItem();
            Product product=new Product();

            try {
                BeanUtils.populate(cartItem,map);
                BeanUtils.populate(product,map);
                cartItem.setProduct(product);
                cartItem.setUser(user);
                cartService.add(cartItem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String url = request.getContextPath()+"/findMyCart";
        return "Redirect:"+url ;
    }


    @URLMapping(url = "/removeCart")
    public String removeCart(HttpServletRequest request, HttpServletResponse response) {
        String pid=request.getParameter("pid");
        cartService.removeCart(pid);
        String url = request.getContextPath()+"/findMyCart";
        return "Redirect:"+url ;
    }

    @URLMapping(url = "/clearCart")
    public String clearCart(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        cartService.clearCart(user.getUid());
        String url = request.getContextPath()+"/findMyCart";
        return "Redirect:"+url ;
    }

}
